<?php

class Core_Table_Road_Info extends Kd_Data_Table {

    private $_relationTable = '{t}road_landmark';

    public function __construct() {
        parent::__construct();
    }

    public function insertRelation($roadId, array $landmarkIds, $transaction = NULL) {
        $insert = Kd_Data_Factory::getInsertDcl()
                        ->into($this->_relationTable)
                        ->value('road_id', "'$roadId'")
                        ->value('landmark_id', ':landmarkId:i')
                        ->toSql();
        $driver = $this->getDbDriver($transaction);
        foreach ($landmarkIds as $landmarkId) {
            $driver->setSql($insert, array('landmarkId' => $landmarkId))->execute();
        }
    }

    public function deleteRelation($roadId, $transaction = NULL) {
        Kd_Data_Factory::getDeleteDcl()
                ->from($this->_relationTable)
                ->where()->eq('road_id', "'$roadId'")->closest()
                ->setDbDriver($this->getDbDriver($transaction))
                ->execute();
    }

    public function getById($id) {
        return Kd_Data_Factory::getQueryDcl()
                ->from($this->getName(), 'a')
                ->rightJoin('{t}foundation_road', 'b', 'b.id', 'a.code')
                ->eq('a.id', ':id:i')
                ->fields('a.*', 'b.province_name', 'b.city_name', 'b.district_name', 'b.townstreet_name', 'b.road_name')
                ->field('b.id', 'road_id')
                ->addParameter('id', $id)
                ->fetch()
                ->getFirstRow();
    }

    public function getByCode($code) {
        return Kd_Data_Factory::getQueryDcl()
                ->from($this->getName(), 'a')
                ->rightJoin('{t}foundation_road', 'b', 'b.id', 'a.code')
                ->eq('b.id', ':code:s')
                ->fields('a.*', 'b.province_name', 'b.city_name', 'b.district_name', 'b.townstreet_name', 'b.road_name')
                ->field('b.id', 'road_id')
                ->addParameter('code', $code)
                ->fetch()
                ->getFirstRow();
    }

}